package cn.snowheart.ssm.service.impl;

import cn.snowheart.ssm.mapper.PersonMapper;
import cn.snowheart.ssm.pojo.Person;
import cn.snowheart.ssm.service.ITestService;
import cn.snowheart.ssm.util.ListUtil;
import cn.snowheart.ssm.util.SpringContextHolder;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author liuwanxiang
 * @version 2018/5/1
 */
@Component
public class TestServiceImpl extends Thread implements ITestService {

    private Logger logger = Logger.getLogger(TestServiceImpl.class);

    @Autowired
    private PersonMapper personMapper;

    private List<Person> persons;

    @Override
    public void insertPerson(Integer count) {

        logger.info(">>> 保存开始，保存个数: " + count);
        long start = System.currentTimeMillis();

        Person person;

        for (int i = 0; i < count; i++) {
            person = new Person();
            person.setAge(i);
            person.setName("name" + i);
            personMapper.insertPerson(person);
        }

        logger.info(">>> 保存结束，保存个数: " + count + " 耗时: " + (System.currentTimeMillis() - start));

    }

    @Override
    public void insertPersonWithThread(Integer count) throws InterruptedException {
        ArrayList<Person> persons = new ArrayList<>();

        Person person;

        for (int i = 0; i < count; i++) {
            person = new Person();
            person.setAge(i);
            person.setName("name" + i);
            persons.add(person);
        }

        List<List<Person>> lists = ListUtil.averageAssign(persons, 10);

        List<Thread> workers = new ArrayList<>();
        for (List<Person> list : lists) {
            Thread worker = new TestServiceImpl(list);
            worker.start();
            workers.add(worker);
        }

        for(int i = 0; i < 10; i++) {
            workers.get(i).join();
        }
        System.out.println("执行主线程");

    }

    public TestServiceImpl() {

    }

    public TestServiceImpl(List<Person> list) {
        this.persons = list;
    }

    @Override
    public void run() {

        if (personMapper == null) {
            personMapper = SpringContextHolder.getBean(PersonMapper.class);
        }

        for (Person person : persons) {
            if (person.getAge() == 399999) {
                person.setAge(1000 / 0);
            }
            personMapper.insertPerson(person);
        }
    }
}
